package com.lawyer.service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dyplsapi.model.v20170525.BindAxgRequest;
import com.aliyuncs.dyplsapi.model.v20170525.BindAxgResponse;
import com.aliyuncs.dyplsapi.model.v20170525.UnbindSubscriptionRequest;
import com.aliyuncs.dyplsapi.model.v20170525.UnbindSubscriptionResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import com.lawyer.config.VirtualCallConfigBean;
import com.lawyer.entity.Config;
import com.lawyer.entity.Coupon;
import com.lawyer.entity.Lawyer;
import com.lawyer.entity.LawyerMicroInfo;
import com.lawyer.entity.MoneyFlows;
import com.lawyer.entity.User;
import com.lawyer.entity.UserMicroInfo;
import com.lawyer.model.Message;
import com.lawyer.model.MessageConstant;
import com.lawyer.repository.CallBlackInfoRepository;
import com.lawyer.repository.ConfigRepository;
import com.lawyer.repository.CouponRepository;
import com.lawyer.repository.LawyerMicroInfoRepository;
import com.lawyer.repository.LawyerMicroScoreInfoRepository;
import com.lawyer.repository.LawyerRepository;
import com.lawyer.repository.MealConfigurationRepository;
import com.lawyer.repository.MoneyFlowsRepository;
import com.lawyer.repository.UserMicroInfoRepository;
import com.lawyer.repository.UserRepository;

@Service
public class VirtualCallService {

	Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private UserRepository userRepository;
	@Autowired
	private LawyerRepository lawyerRepository;

	@Autowired
	private UserMicroInfoRepository userMicroInfoRepository;
	@Autowired
	private LawyerMicroInfoRepository lawyerMicroInfoRepository;

	@Autowired
	private MoneyFlowsRepository moneyFlowsRepository;

	@Autowired
	private MealConfigurationRepository mealConfigurationRepository;

	@Autowired
	private LawyerMicroScoreInfoRepository lawyerMicroScoreInfoRepository;

	@Autowired
	private CouponRepository couponRepository;
	@Autowired
	private ConfigRepository configRepository;

	@Autowired
	private PushService pushService;

	@Autowired
	private CallBlackInfoRepository callBlackInfoRepository;

	@Autowired
	private VirtualCallConfigBean virtualCallConfigBean;

	/**
	 * 通话结算
	 * 
	 * @param userId
	 * @param lawyerId
	 * @param couponId
	 * @return
	 */
	public Message callSettlement(String userId, String lawyerId, Integer couponId) {
		Message msg = new Message();
		Double userChangeMoney = 0D;
		Double lawyerChangeMoney = 0D;
		MoneyFlows userFlow = new MoneyFlows();
		try {
			Lawyer lawyer = lawyerRepository.findOne(lawyerId);
			User user = userRepository.findOne(userId);
			if (user != null) {
				// 用优惠券
				if (couponId != null) {
					Coupon coupon = couponRepository.findByUserIdAndIsUsedAndId(userId, false, couponId);
					if (coupon != null) {

						Config config = configRepository.findByName("Subsidies");// 免费咨询律师补贴费用配置
						lawyerChangeMoney = Double.valueOf(config.getValue());
						// 设置律师收益，免费券律师收益5元
						lawyer.setBalance(lawyer.getBalance() + lawyerChangeMoney);
						userFlow.setDescription("使用免费咨询券");
						userFlow.setChangeMoney(0D);

						// 设置优惠券为已使用
						coupon.setIsUsed(true);
						couponRepository.save(coupon);
					}

				} else {
					// 按120元/次记费
					Config config5 = configRepository.findByName("ConsultingFee");// 律师咨询费
					Double pay = Double.valueOf(config5.getValue());// 律师咨询费用
					userChangeMoney = Double.valueOf(config5.getValue());

					if (pay > user.getBalance()) {
						msg.setCode(MessageConstant.FAILED_CODE);
						msg.setMessage("余额不足,请充值");
						logger.info("通话结算余额不足,请充值");
						return msg;
					}
					Config config = configRepository.findByName("TelephoneCounseling");// 律师费用分成比例配置
					// 设置律师收益
					Double rate = Double.valueOf(config.getValue());
					// 律师最终收益
					Double multiplyResult = pay * rate;
					
					lawyerChangeMoney = new BigDecimal(multiplyResult).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
					
					lawyer.setBalance(lawyer.getBalance() + lawyerChangeMoney);

					userFlow.setDescription("扣除咨询费");
					userFlow.setChangeMoney(0 - userChangeMoney);
				}

				user.setBalance(user.getBalance() - userChangeMoney);// 扣除余额
				userRepository.save(user);

				lawyerRepository.save(lawyer);
				// 用户金钱变更记录
				userFlow.setTypeFlow(1);
				
				userFlow.setUserId(userId);
				userFlow.setUserName(user.getNickName());
				userFlow.setLawyerId(lawyerId);
				userFlow.setLawyerName(lawyer.getNickName());
				
				userFlow.setUserName(user.getNickName());
				userFlow.setPhone(user.getPhone());
				userFlow.setUserType(user.getUserType());
				moneyFlowsRepository.save(userFlow);

				// 用户通话记录
				UserMicroInfo userMaiInfo = new UserMicroInfo();
				userMaiInfo.setUserId(userId);
				userMaiInfo.setLawyerHeaderUrl(lawyer.getHeaderIco());
				userMaiInfo.setLawyerName(lawyer.getNickName());
				userMaiInfo.setPrice(userChangeMoney);
				userMaiInfo.setLawyerId(lawyerId);
				userMaiInfo.setCouponId(couponId);
				userMicroInfoRepository.save(userMaiInfo);

				// 律师金钱变更记录
				MoneyFlows lawyerFlow = new MoneyFlows();
				lawyerFlow.setTypeFlow(2);
				lawyerFlow.setUserType("2");
				lawyerFlow.setUserId(user.getId());
				lawyerFlow.setUserName(user.getNickName());
				
				lawyerFlow.setLawyerId(lawyerId);
				lawyerFlow.setLawyerName(lawyer.getNickName());
				
				lawyerFlow.setChangeMoney(lawyerChangeMoney);
				lawyerFlow.setDescription("语音咨询收益");
				lawyerFlow.setPhone(lawyer.getPhone());
				moneyFlowsRepository.save(lawyerFlow);

				// 律师通话记录
				LawyerMicroInfo lawyerMicroInfo = new LawyerMicroInfo();
				lawyerMicroInfo.setUserHeaderUrl(user.getHeaderIco());
				lawyerMicroInfo.setNickName(user.getNickName());
				lawyerMicroInfo.setPrice(userChangeMoney);
				lawyerMicroInfo.setUserId(userId);
				lawyerMicroInfo.setLawyerId(lawyerId);
				lawyerMicroInfo.setEarnings(lawyerChangeMoney);
				lawyerMicroInfo.setCouponId(couponId);
				lawyerMicroInfoRepository.save(lawyerMicroInfo);

			} else {
				msg.setCode(MessageConstant.FAILED_CODE);
				msg.setMessage("账号不存在");
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage(MessageConstant.FAILED_MSG);
		}
		logger.info("通话结算====" + new Gson().toJson(msg));
		return msg;
	}

	/**
	 * @param from
	 *            :phoneA
	 * @param to
	 *            :phoneB
	 * @return
	 */
	public BindAxgResponse bindAxG(String phoneA, String phoneB, String userId, String lawyerId, Integer couponId) {
		User user = userRepository.findOne(userId);
		String paramater = userId + "&" + lawyerId + "&" + couponId;
		BindAxgResponse response = null;
		DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", virtualCallConfigBean.getAccessKeyId(), virtualCallConfigBean.getAccessSecret());
		IAcsClient client = new DefaultAcsClient(profile);

		BindAxgRequest request = new BindAxgRequest();
		request.setRegionId("cn-hangzhou");
		// 绑定关系的过期时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar nowTime = Calendar.getInstance();
		nowTime.add(Calendar.MINUTE, 5);// 五分钟
		request.setExpiration(sdf.format(nowTime.getTime()));
		// 请登录号码隐私保护控制台，在号码池管理中查看号码池Key。
		request.setPoolKey(virtualCallConfigBean.getPoolKey());
		request.setPhoneNoA(phoneA);
		request.setPhoneNoB(phoneB);
		request.setGroupId(virtualCallConfigBean.getGourpId());
		request.setOutId(paramater);// 用户id+律师ID

		try {
			response = client.getAcsResponse(request);
			logger.info("绑定bindAxG返回数据====" + new Gson().toJson(response));
			System.out.println(new Gson().toJson(response));
			if ("OK".equals(response.getMessage())) {

				user.setSecretNo(response.getSecretBindDTO().getSecretNo());
				user.setSubsId(response.getSecretBindDTO().getSubsId());
				userRepository.save(user);
			}
		} catch (ServerException e) {
			e.printStackTrace();
		} catch (ClientException e) {
			System.out.println("ErrCode:" + e.getErrCode());
			System.out.println("ErrMsg:" + e.getErrMsg());
			System.out.println("RequestId:" + e.getRequestId());
		}
		return response;

	}

	/**
	 * 订购关系解绑示例(解绑接口不区分AXB、AXN)
	 *
	 * @return
	 * @throws ClientException
	 */
	public UnbindSubscriptionResponse unbind(String subsId, String secretNo) {

		DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", virtualCallConfigBean.getAccessKeyId(), virtualCallConfigBean.getAccessSecret());
		IAcsClient client = new DefaultAcsClient(profile);

		UnbindSubscriptionRequest request = new UnbindSubscriptionRequest();
		request.setRegionId("cn-hangzhou");
		request.setPoolKey(virtualCallConfigBean.getPoolKey());
		// 隐私号码。调用BindAXG等号码绑定接口时指定或自动分配的X号码。
		request.setSecretNo(secretNo);
		// 绑定关系ID,可以在控制台的号码管理 >
		// 号码详情中查看绑定关系ID，或者在调用BindAxb等号码绑定API时查看返回参数中的SubsId。
		request.setSubsId(subsId);

		try {
			UnbindSubscriptionResponse response = client.getAcsResponse(request);
			response = client.getAcsResponse(request);
			logger.info("解绑返回数据====" + new Gson().toJson(response));
			return response;
		} catch (ServerException e) {
			e.printStackTrace();
		} catch (ClientException e) {
			System.out.println("ErrCode:" + e.getErrCode());
			System.out.println("ErrMsg:" + e.getErrMsg());
			System.out.println("RequestId:" + e.getRequestId());
		}
		return null;
	}

}
